package com.coisshi.base.module.upload.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.coisshi.base.common.exception.BizException;
import com.coisshi.base.framework.config.properties.UploadProperties;
import com.coisshi.base.module.upload.service.UploadService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 上传服务实现
 */
@Service
@RequiredArgsConstructor
public class UploadServiceImpl implements UploadService {

    private final UploadProperties uploadProperties;

    @Override
    public String upload(MultipartFile file) throws BizException {
        return saveFile(file);
    }

    @Override
    public List<String> uploadBatch(List<MultipartFile> files) throws BizException {
        if (files == null || files.isEmpty()) {
            throw new BizException("上传文件列表不能为空");
        }
        List<String> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            urls.add(saveFile(file));
        }
        return urls;
    }

    /**
     * 保存文件的核心方法
     * @param file MultipartFile
     * @return 文件URL
     */
    private String saveFile(MultipartFile file) throws BizException {
        if (file.isEmpty()) {
            throw new BizException("上传文件不能为空");
        }

        if (file.getSize() > uploadProperties.getMaxSize()) {
            throw new BizException("上传文件大小不能超过" + (uploadProperties.getMaxSize() / 1024 / 1024) + "MB");
        }

        String originalFilename = file.getOriginalFilename();
        String extName = Objects.requireNonNull(FileUtil.extName(originalFilename)).toLowerCase();
        boolean allowed = false;
        for (String type : uploadProperties.getAllowedTypes()) {
            if (type.equals(extName)) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            throw new BizException("不支持的文件类型: " + extName);
        }

        File uploadDir = new File(uploadProperties.getUploadDir());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String newFileName = IdUtil.simpleUUID() + "." + extName;
        try {
            File destFile = new File(uploadDir, newFileName);
            file.transferTo(destFile);
        } catch (Exception e) {
            throw new BizException("文件保存失败" + e.getMessage());
        }

        return uploadProperties.getDomain() + uploadProperties.getBasePath() + newFileName;
    }
} 